<?php 
  require_once("../includes/config.php"); 
  $length = 20;
 
  if( isset($_GET['check']) && $_GET['check'] == 'on' )
  {
    $check = 1;
  }
  else
  {
    $check = 0;
  }
  
  if( isset($_GET['page'])  && !empty($_GET['page'] ))
  {
    $page =  filter_var($_GET['page'], FILTER_SANITIZE_NUMBER_INT);
    $start = $page*20 - 20;
  }
  else
  {
    $start = 0;
    $page = 1;
  }
  
  if( $check == 1 )
  {
    $sql = 'SELECT * FROM companies WHERE owner_id = ?';
    $sqlCount = 'SELECT COUNT(*) FROM companies WHERE owner_id = ?';
  }
  else
  {
    $sql = 'SELECT * FROM clients WHERE owner_id = ?';
    $sqlCount = 'SELECT COUNT(*) FROM clients WHERE owner_id = ?';
  }
  $binds = array();
  
  $binds['owner_id'] = $_SESSION['user_id'];   
  
  if ( (!empty($_GET['name'])) || (!empty($_GET['id'])) || (!empty($_GET['mobile'])) ) 
  {
    if(!empty($_GET['name']))
    {
      if(!empty($binds))
        $and = " and ";
      else
        $and = " ";
        
      $binds['name'] = "%".$_GET['name']."%";
      
      if( $check == 1 )
      {
        $sql .= $and."company_name LIKE ?";
        $sqlCount .=$and. "company_name LIKE ?";
      }       
      else
      {
        $sql .= $and." name LIKE ?";
        $sqlCount .=$and. " name LIKE ?";
      }
    } 
          
    if(!empty($_GET['id']))
    {
      if(!empty($binds))
        $and = " and ";
      else
        $and = " ";
            
      $binds['id'] = $_GET['id'];
      
      if( $check == 1 )
      {
        $sql .= $and."company_phone = ?";
        $sqlCount .= $and."company_phone = ?";
      }       
      else
      {
        $sql .= $and."identification_number  = ?";
        $sqlCount .= $and."identification_number  = ?";
      }
    }
          
    if(!empty($_GET['mobile']))
    {
      if(!empty($binds))
        $and = " and ";
      else
        $and = " ";
            
      $binds['mobile'] = $_GET['mobile'];
      if( $check == 1 )
      {
        $sql .= $and."company_phone = ?";
        $sqlCount .= $and."company_phone = ?";
      }       
      else
      {
        $sql .= $and."mobile = ?";
        $sqlCount .= $and."mobile = ?";
      }
    }
  }   
  $sql .= " LIMIT ?,?";
  $binds['start'] = $start;
  $binds['end'] = $length;

  $clients = query($sql,$binds);
  $Count = query($sqlCount,$binds);
  $totalPages = $Count[0]['COUNT(*)'];
  
  
  $nationalities = query('SELECT * FROM nationalities ORDER BY nationality_value');
	if(!empty($_GET['name']))
	   $binds['name'] = $_GET['name'];
  render("customers.php", array("title"=>"إدارة العملاء","clients"=>$clients,"totalPages"=>$totalPages,"page"=>$page,"check"=>$check,"client_type"=>$client_type,"nationalities"=>$nationalities,"binds"=>$binds));



?>